<template>
  <el-form
    size="medium"
    class="padding-20px"
    :model="form"
    :rules="rules"
    ref="form"
  >
    <el-form-item prop="account">
      <el-input :placeholder="$t('login.account')" v-model="form.account" />
    </el-form-item>
    <el-form-item prop="password">
      <el-input
        show-password
        :placeholder="$t('login.password')"
        v-model="form.password"
      ></el-input>
    </el-form-item>
    <el-form-item>
      <button type="button" role="primary" class="w-100" @click="submit()">
        {{ $t('login.login') }}
      </button>
      <div class="float-l">
        <input type="checkbox" v-model="isRememberAccount">{{$t('login.rememberAccount')}}
      </div>
      <router-link to="/register" class="float-r">{{
        $t('login.signUp')
      }}</router-link>
    </el-form-item>
  </el-form>
</template>
<script>
import { login } from '@/assets/api/index'
const BLUR = 'blur'
export default {
  data () {
    return {
      form: { account: localStorage.getItem('isRememberAccount') === 'true' ? localStorage.getItem('account') : '' },
      isRememberAccount: localStorage.getItem('isRememberAccount') || false,
      rules: {
        account: [
          {
            required: true,
            trigger: BLUR,
            message: this.$t('validationMessage.inputRequired')
          },
          {
            type: 'email',
            trigger: BLUR,
            message: this.$t('validationMessage.emailFormat')
          }
        ],
        password: [
          {
            required: true,
            trigger: BLUR,
            message: this.$t('validationMessage.inputRequired')
          },
          {
            min: 6,
            max: 12,
            trigger: BLUR,
            message: this.$t('validationMessage.lengthRange', {
              min: 6,
              max: 12
            })
          }
        ]
      }
    }
  },
  mounted () {
    const VueObj = this
    document.addEventListener('keydown', (e) => {
      var ev = window.event || e
      var code = ev.keyCode || ev.which
      if (event.key === 'Enter' && code === 13) {
        VueObj.submit()
      }
    })
  },
  methods: {
    submit () {
      localStorage.setItem('isRememberAccount', this.isRememberAccount)
      localStorage.setItem('account', this.form.account)
      this.$refs.form.validate(valid => {
        if (valid) {
          login(this.form).then(res => {
            if (res.data) {
              localStorage.setItem('token', res.data)
              this.$router.push({ path: '/home' })
            } else {
              this.$message({
                type: 'warning',
                message: this.$t('login.loginFailed')
              })
            }
          })
        }
      })
    }
  }
}
</script>
